package com.limeng.datastruts.sort;

import java.util.Arrays;

public class BubbleSort {
    public static void main(String[] args) {
        int[] nums = new int[]{5, 8, 6, 3, 9, 2, 1, 7};

        BubbleSort bubbleSort = new BubbleSort();
        bubbleSort.directBubbleSort(nums);
        System.out.println(Arrays.toString(nums));
    }

    /**
     * 冒泡排序
     * @param nums
     */
    public void directBubbleSort(int[] nums) {

        for (int i = 0; i < nums.length; i++) {
            boolean isSort = true;//默认是已经排好的
            //已经移到右侧的就不用了比较了，所以需要 -i
            for (int j = 0; j < nums.length - i - 1; j++) {
                if (nums[j] > nums[j + 1]) {
                    isSort = false;
                    int tmp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = tmp;
                }
            }
            if (isSort) break;
        }
    }

}
